package T11_new_lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class T10_new_lock_test {    
    public static void main(String[] args) {    
        MyCount myCount = new MyCount("2008", 10000); 
        Lock lock = new ReentrantLock();    
        ExecutorService pool = Executors.newCachedThreadPool();    
        User u1 = new User("lang1", myCount, -4000, lock);    
        User u2 = new User("lang2", myCount, 6000, lock);    
        User u3 = new User("lang3", myCount, -8000, lock);    
        User u4 = new User("lang4", myCount, 800, lock);    
        pool.execute(u1);    
        pool.execute(u2);    
        pool.execute(u3);    
        pool.execute(u4);  
        pool.shutdown();    
    }    
}    
class User implements Runnable {    
	private String name;               
	private MyCount myCount;       
	private int iocash;              
	private Lock myLock;              
	User(String name, MyCount myCount, int iocash, Lock myLock) {    
        this.name = name;    
        this.myCount = myCount;    
        this.iocash = iocash;    
        this.myLock = myLock;    
	}    
	public void run() {    
        myLock.lock();    
        System.out.println(name + "正在操作" + myCount + " 账户，金额为          " 
        		+ iocash + "，当前金额为" + myCount.getCash());    
        myCount.setCash(myCount.getCash() + iocash);    
        System.out.println(name + "操作          " + myCount + " 账户成功，金额为" 
        		+ iocash + "，当前金额为" + myCount.getCash());    
        myLock.unlock();    
	}    
}    
class MyCount {    
	private String oid;        
	private int cash;            
	MyCount(String oid, int cash) {    
        this.oid = oid;    
        this.cash = cash;    
	}    
	public String getOid() {    
        return oid;    
	}    
	public void setOid(String oid) {    
        this.oid = oid;    
	}    
	public int getCash() {    
        return cash;    
	}    
	public void setCash(int cash) {    
        this.cash = cash;    
	}    
	@Override    
	public String toString() {    
		return "MyCount{" + "oid='" + oid + '\'' +  ", cash=" + cash +    '}';    
	}    

}
